<?php


namespace app\admin\controller;


use think\Exception;

class Review extends Base
{
    public function __construct()
    {
        parent::__construct();
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);
    }

    public function index()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $list = db('review')->order('id', 'desc')->paginate($param['limit']);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());
        $this->assign('param', $param);
        return $this->fetch('admin@review/index');
    }

    /**
     * 添加好评设备
     */
    public function info()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $appId = input('app_id', '', 'trim');
        $count = db('banben')->where('app_id', $appId)->count() ?: 0;
        $message = "";
        if (empty($appId) || $count < 1) {
            $message .= " 请选择应用";
        }
        $vodNum = input('vod_num', 0, 'intval');
        $zhiboNum = input('zhibo_num', 0, 'intval');

        if ($vodNum < 0 || $zhiboNum < 0) {
            $message .= " 影片或者直播数量不能设置为负数";
        }

        $days = input('days', 0, 'intval');
        if (empty($days) || $days < 1) {
            $message = "有效登陆天数有误！";
        }
        if (request()->isAjax()) {
            if (!empty($message)) {
                $this->error($message);
            }
            $time = time();
            db()->startTrans();
            try {
                $reviewId = db('review')->insertGetId([
                    'app_id' => $appId,
                    'reg_days' => $days,
                    'vod_num' => $vodNum,
                    'zhibo_num' => $zhiboNum,
                    'time_added' => $time,
                    'time_updated' => $time
                ]);
                $lastPage = 100;
                for ($i = 1; $i < $lastPage; $i++) {
                    $devices = [];
                    $list = db('device_date')->alias('dd')->join('device d', 'd.app_id = dd.app_id and d.device_id = dd.device_id', 'LEFT')->where('dd.app_id', $appId)->where('d.vod_num', ">=", $vodNum)->where('d.zhibo_num', ">=", $zhiboNum)->field('dd.app_id,dd.device_id,d.device_name,d.vod_num,d.jiguang_id,d.zhibo_num,d.time_added,count(dd.id) as reg_days')->where('review_status', 0)->having('count(dd.id) >=' . $days)->group('dd.device_id')->orderRaw('count(dd.id) desc')->orderRaw('(d.vod_num + d.zhibo_num) desc')->order('d.vod_num', 'desc')->order('d.zhibo_num', 'desc')->paginate(2000, false, ['page' => $i]);
                    if ($list->isEmpty()) {
                        break;
                    }
                    foreach ($list as $item) {
                        $item['review_id'] = $reviewId;
                        $item['time_added'] = $time;
                        $item['time_updated'] = $time;
                        $item['is_show'] = 1;
                        $devices[] = $item;
                    }
                    db('review_device')->insertAll($devices, 500);
                }
                //更新设备数量
                $this->updateReview($reviewId);
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                $this->error($e->getMessage());
            }
            $this->success('success');

        } else {
            if ($count == 1) {
                $list = db('device_date')->alias('dd')->join('device d', 'd.app_id = dd.app_id and d.device_id = dd.device_id', 'LEFT')->where('dd.app_id', $appId)->where('d.vod_num', ">=", $vodNum)->where('d.zhibo_num', ">=", $zhiboNum)->field('dd.device_id,d.device_name,d.vod_num,d.jiguang_id,d.zhibo_num,d.time_added,count(dd.id) as reg_days')->where('review_status', 0)->having('count(dd.id) >=' . $days)->group('dd.device_id')->orderRaw('count(dd.id) desc')->orderRaw('(d.vod_num + d.zhibo_num) desc')->order('d.vod_num', 'desc')->order('d.zhibo_num', 'desc')->paginate($param['limit']);
                $param['page'] = '{page}';
                $param['limit'] = '{limit}';
                $this->assign('list', $list->items());
                $this->assign('total', $list->total());
                $this->assign('page', $list->currentPage());
                $this->assign('limit', $list->listRows());
            } else {
                $this->assign('list', []);
                $this->assign('total', 0);
                $this->assign('page', 1);
                $this->assign('limit', $param['limit']);
            }
            $this->assign('message', $message);
            $this->assign('param', $param);
            return $this->fetch("admin@review/info");
        }
    }

    /**
     * 设备列表
     */
    public function list()
    {
        $param = input();
        $reviewId = $param['review_id'];
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $list = db('review_device')->where('review_id', $reviewId)->paginate($param['limit']);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());
        $this->assign('param', $param);
        return $this->fetch('admin@review/list');
    }

    /**
     * 待处理列表
     * @return mixed
     * @throws \think\db\exception\DbException
     * @throws \think\exception\DbException
     */
    public function needDo()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $list = db('review_device')->whereNotNull('pic')->where('is_rewarded',0)->paginate($param['limit']);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());
        $this->assign('param', $param);
        return $this->fetch('admin@review/needdo');
    }

    /**
     * 设置免广告
     */
    public function adFree()
    {
        $id = input('id');
        $reviewDeviceInfo = db('review_device')->where('id', $id)->find();
        if (empty($reviewDeviceInfo)) {
            $this->error('数据有误！');
        }

        $reviewId = $reviewDeviceInfo['review_id'];

        $deviceInfo = db('device')->where('app_id', $reviewDeviceInfo['app_id'])->where('device_id', $reviewDeviceInfo['device_id'])->find();
        if ($deviceInfo['review_status'] == 1) {
            $this->error('已经给该用户发放过奖励了');
        }
        db()->startTrans();
        try {
            $aWeekTime = strtotime("+1 week");
            $pointsArray = [
                'app_id' => $reviewDeviceInfo['app_id'],
                'device_id' => $reviewDeviceInfo['device_id'],
                'points' => 0,
                'memo' => '参与好评活动 获得免广告权利，有效期至' . date('Y-m-d H:i'),
                'type' => 'review',
                'date' => date('Y-m-d'),
                'time_added' => time()
            ];
            db('points')->insertGetId($pointsArray);
            db('device')->where('app_id', $reviewDeviceInfo['app_id'])->where('device_id', $reviewDeviceInfo['device_id'])->update([
                'review_status' => 1,//更新设备表状态
                'time_expired' => $aWeekTime,//发放奖励
            ]);
            db('review_device')->where('id', $reviewDeviceInfo['id'])->update([
                "is_rewarded" => 1
            ]);
            $this->updateReview($reviewId);
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
        }
        $return = $this->sendJpush($reviewDeviceInfo,$deviceInfo,true);

        if($return['code']==0){
            $this->error("发放成功，激光发送失败！".$return['return']);
        }
        //处理极光发送状态
        db('review_device')->where('id', $reviewDeviceInfo['id'])->update([
            "jpush_status" => 1,
            "time_updated" => time(),
            "jpush_data" => json_encode($return['return']['body'], JSON_UNESCAPED_UNICODE)
        ]);
        $this->success('操作成功，极光推送发送成功！');
    }

    public function updateReview($reviewId)
    {
        if ($reviewId < 1) {
            $this->error('数据有误！');
        }
        $reviewInfo = db('review')->where('id', $reviewId)->find();
        if (empty($reviewInfo)) {
            $this->error('数据有误！');
        }
        //更新设备数量
        $count = db('review_device')->where('review_id', $reviewId)->count() ?: 0;
        $showCount = db('review_device')->where('review_id', $reviewId)->where('is_show', 0)->count() ?: 0;
        $uploadCount = db('review_device')->where('review_id', $reviewId)->whereNotNull('pic')->count() ?: 0;
        $doCount = db('review_device')->where('review_id', $reviewId)->where('is_rewarded', 1)->count() ?: 0;
        db('review')->where('id', $reviewId)->update([
            'device_num' => $count,
            'show_num' => $showCount,
            'upload_num' => $uploadCount,
            'do_num' => $doCount,
        ]);
    }

    public function sendJpush($reviewDeviceInfo,$deviceInfo,$return = false){
            //发送激光推送
            $jpush = new \app\app\controller\Jpush();
            $pushInfo = [
                'app_id' => $deviceInfo['app_id'],
                'jiguang_id' => $deviceInfo['jiguang_id'],
                'content' => '您参与的好评免广告活动已经审核通过，免广告截止时间' . date('Y-m-d H:i'),
                'title' => '您已获得免广告一周',
                'system_type' => $deviceInfo['system_type']
            ];
            $jiguangInfo = $jpush->jiguangAppIds[$pushInfo['app_id']];
            switch ($pushInfo['system_type']) {
                case 'ios':
                    $return = $jpush->sednjiaungIOS($jiguangInfo['jpush_app_key'], $jiguangInfo['jpush_master_secret'], $pushInfo['content'], $pushInfo['title'], $pushInfo['jiguang_id'], ['vod_id' => $pushInfo['vod_id']]);
                    break;
                case 'android':
                    $return = $jpush->sednjiaungAndroid($jiguangInfo['jpush_app_key'], $jiguangInfo['jpush_master_secret'], $pushInfo['content'], $pushInfo['title'], $pushInfo['jiguang_id'], ['vod_id' => $pushInfo['vod_id']]);
                    break;
            }
            return $return;

    }
}